package org.yankun.exam4j.session;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 用于存储登录用户的数据。
 * @author wyz
 *
 */
public final class UserSessionData implements Serializable, HttpSessionActivationListener {

	private static final long serialVersionUID = -5523968479671353896L;
	
	public static final String ATTR_USER_SESSION_DATA_RESTORE_QUEUE = "__user_session_data_restore_queue__";
	
	private transient ServletContext sc;

	
	private String sessionId;
	private Serializable userId;
	private String username;
	private boolean isWhiteIp;
	private boolean isAdmin;
	public boolean isAdmin() {
		return isAdmin;
	}


	protected void setAdmin(boolean isAdmin) {
		this.isAdmin = isAdmin;
	}


	private Set<String> authorities;
	
	 public UserSessionData(String sessionId, Serializable userId, String username,boolean isAdmin) {
		 assert (sessionId != null);
		 assert (userId != null);
		 this.sessionId = sessionId;
		 this.userId = userId;
		 this.username = username;
		 this.isAdmin = isAdmin;
	 }

	 
	/**
	 * 获取用户主键 id
	 * @return
	 */
	public Serializable getUserId() {
		return userId;
	}
	

	/**
	 * 获取用户所拥有的所有权限集合
	 */
	public Set<String> getAuthorities() {
		return authorities;
	}
	
	
	/**
	 * 设置用户的权限集合
	 * @param authorities
	 */
	public void setAuthorities(Set<String> authorities) {
		this.authorities = authorities;
	}
	
	
	/**
	 * 获取用户会话id
	 * @return
	 */
	public String getSessionId() {
		return sessionId;
	}
	
	@Override
	public int hashCode() {
		return userId.hashCode() ^ sessionId.hashCode();
	}

  
	/**
	 * 指示会话已从持久化状态中恢复
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void sessionDidActivate(HttpSessionEvent e) {
		this.sc = e.getSession().getServletContext();
		ApplicationContext ac =  WebApplicationContextUtils.getWebApplicationContext(sc);
		if (ac == null) {
			ArrayList<UserSessionData> al = (ArrayList<UserSessionData>)sc.getAttribute(ATTR_USER_SESSION_DATA_RESTORE_QUEUE);
			if (al == null) { 
				al = new ArrayList<UserSessionData>(128);
			}
			al.add(this);
		}
	}


	/**
	 * 指示会话将被持久化，暂不做任何动作
	 */
	@Override
	public void sessionWillPassivate(HttpSessionEvent e) {
		
	}


	public String getUsername() {
		return username;
	}


	public boolean isWhiteIp() {
		return isWhiteIp;
	}


	public void setWhiteIp(boolean isWhiteIp) {
		this.isWhiteIp = isWhiteIp;
	}
	
}
